"""
共享内存: 单独开辟一个共享内存空间
    共享内存只能有一个值
"""

from multiprocessing import Process, Value, Array
import time
import random


# 创建共享内存
money = Value('i', 5000)
lie = Array('i', [1,2,3,4,5,6,7,8])  # 开辟具有初始值的整型列表
# lie = Array('i', 5)  # 开辟包含5个元素的整型列表

#%% 操作共享内存
def man():
    for i in range(30):
        time.sleep(0.2)
        money.value += random.randint(1, 1000)
    print(f"挣了: {money.value}快钱.")

def girl():
    for i in range(30):
        time.sleep(0.15)
        money.value -= random.randint(100, 800)  # 花的钱
    print(f"还剩了: {money.value}快钱.")
    

#%% 开辟内存空间
def fun():
    for i in lie:
        print(i)
    lie[1] = 22  # 在子进程中修改了,父进程的列表也会相应的修改
        

lk = [man, girl, fun]
ls = []
for i in lk:
    sk = Process(target=i)
    sk.start()
    ls.append(i)
if ls:
    for c in ls:
        sk.join()

print("一个月后的余额: ", money.value)
for d in lie:
    print(d)